package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.mapper.XcUserRoleMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.model.po.XcUserRole;
import com.xuecheng.ucenter.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;
@Service("email_authservice")
public class EmailAuthServiceImpl implements AuthService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    XcUserMapper xcUserMapper;
    @Autowired
    XcUserRoleMapper xcUserRoleMapper;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        String checkcodekey = authParamsDto.getCheckcodekey();//验证码的key就是用户的邮箱
        String s = redisTemplate.opsForValue().get("mailCheckCode:"+checkcodekey).toString();
        if (StringUtils.isNotBlank(s) && StringUtils.isNotBlank(authParamsDto.getCheckcode()) && authParamsDto.getCheckcode().equals(s)) {
            //判断是否为新用户
            XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>()
                    .eq(XcUser::getEmail, checkcodekey));
            if (xcUser != null) {
                XcUserExt xcUserExt = new XcUserExt();
                BeanUtils.copyProperties(xcUser,xcUserExt);
                return xcUserExt;
            }
            //是新用户要插入到数据库
            XcUser user = new XcUser();
            String userId = UUID.randomUUID().toString();
            user.setId(userId);
            user.setUsername(checkcodekey);
            user.setName(checkcodekey);
            user.setPassword(checkcodekey);
            user.setEmail(checkcodekey);
            user.setUtype("101001");//学生类型
            user.setStatus("1");//用户状态
            user.setCreateTime(LocalDateTime.now());
            xcUserMapper.insert(user);
            XcUserRole xcUserRole = new XcUserRole();
            xcUserRole.setId(UUID.randomUUID().toString());
            xcUserRole.setUserId(userId);
            xcUserRole.setRoleId("17");//学生角色
            xcUserRoleMapper.insert(xcUserRole);
            XcUserExt xcUserExt = new XcUserExt();
            BeanUtils.copyProperties(xcUser,xcUserExt);
            return xcUserExt;
        }else {
            throw new RuntimeException("验证码错误！");
        }
    }
}
